package org.demo.base.config;

import javax.inject.Inject;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.core.env.Environment;

@Configuration
@Profile("testing")
public class JNDIDataConfiguration {

    /* ---- Instance Variables ---- */
    @Inject private Environment environment;


    /* ---- Configuration Beans ---- */

    /**
     * DONT forget to configure the datasource in the \conf\context.xml file:
     *
     *   <Resource name="jdbc/demo" auth="Container" type="javax.sql.DataSource"
     *       maxActive="100" maxIdle="30" maxWait="10000"
     *       username="root" password="mysql" driverClassName="com.mysql.jdbc.Driver"
     *       url="jdbc:mysql://localhost:3306/demo"/>
     *
     */


    @Bean
    public DataSource dataSource() {
        DataSource dataSource;
        try {
            Context ctx = new InitialContext();
            Context envCtx = (Context) ctx.lookup("java:comp/env");
            String name = this.environment.getProperty("datasource.jndiName");
            dataSource = (DataSource) envCtx.lookup("jdbc/demo");
            System.out.println(dataSource);
        } catch (Exception e) {
            throw new IllegalStateException("Failed to create a dataSource", e);
        }
        return dataSource;
    }

}
